'use strict';

const crypto = require('crypto');

exports.main = async (event, context) => {
  const { action, ...params } = event;
  
  try {
    switch(action) {
      case 'createAdmin':
        return await createAdmin(params, context);
      case 'listUsers':
        return await listUsers(params, context);
      case 'updateUser':
        return await updateUser(params, context);
      case 'deleteUser':
        return await deleteUser(params, context);
      case 'getUserDetail':
        return await getUserDetail(params, context);
      case 'getUserStats':
        return await getUserStats(params, context);
      case 'getViolations':
        return await getViolations(params, context);
      case 'getViolationStats':
        return await getViolationStats(params, context);
      case 'addViolation':
        return await addViolation(params, context);
      case 'deleteViolation':
        return await deleteViolation(params, context);
      case 'getPendingAudits':
        return await getPendingAudits(params, context);
      case 'auditContent':
        return await auditContent(params, context);
      case 'getAuditHistory':
        return await getAuditHistory(params, context);
      case 'getAuditStats':
        return await getAuditStats(params, context);
      case 'getRejectedContent':
        return await getRejectedContent(params, context);
      case 'restoreRejectedContent':
        return await restoreRejectedContent(params, context);
      case 'deleteRejectedContent':
        return await deleteRejectedContent(params, context);
      default:
        return { code: 400, msg: '不支持的操作' };
    }
  } catch(e) {
    console.error('云函数执行错误:', e);
    return { code: 500, msg: e.message || '服务器内部错误' };
  }
};

// 创建管理员用户
async function createAdmin(params, context) {
  const { username, password, nickname } = params;
  
  if(!username || !password) {
    return { code: 400, msg: '用户名和密码不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    // 检查用户是否已存在
    const existQuery = await usersCollection.where({
      username: username
    }).get();
    
    if(existQuery.data && existQuery.data.length > 0) {
      return { code: 400, msg: '用户已存在' };
    }
    
    // 加密密码
    const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');
    
    // 创建用户
    const createRes = await usersCollection.add({
      username: username,
      password: hashedPassword,
      nickname: nickname || username,
      role: ['admin'],
      status: 0, // 0: 正常, 1: 禁用
      avatar: '/static/logo.png',
      email: '',
      mobile: '',
      register_date: new Date(), // 修正：使用 register_date 并且使用 Date 对象
      last_login_date: null,
      last_login_ip: ''
    });
    
    if(createRes.id) {
      return {
        code: 0,
        data: {
          _id: createRes.id,
          username: username,
          nickname: nickname || username,
          role: ['admin']
        },
        msg: '管理员用户创建成功'
      };
    } else {
      return { code: 500, msg: '用户创建失败' };
    }
  } catch(e) {
    console.error('创建管理员失败:', e);
    return { code: 500, msg: '创建管理员失败: ' + e.message };
  }
}

// 获取用户列表
async function listUsers(params, context) {
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    const result = await usersCollection
      .field({
        username: true,
        nickname: true,
        role: true,
        status: true,
        register_date: true, // 修正：使用 register_date 而不是 create_date
        last_login_date: true,
        email: true,
        mobile: true,
        violation_count: true,
        violation_records: true
      })
      .orderBy('register_date', 'desc') // 修正：使用 register_date 排序
      .get();
    
    return {
      code: 0,
      data: result.data || [],
      msg: '获取用户列表成功'
    };
  } catch(e) {
    console.error('获取用户列表失败:', e);
    return { code: 500, msg: '获取用户列表失败: ' + e.message };
  }
}

// 更新用户信息
async function updateUser(params, context) {
  const { userId, updates } = params;
  
  if(!userId) {
    return { code: 400, msg: '用户ID不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    // 如果更新密码，需要加密
    if(updates.password) {
      updates.password = crypto.createHash('sha256').update(updates.password).digest('hex');
    }
    
    const updateRes = await usersCollection.doc(userId).update(updates);
    
    return {
      code: 0,
      data: updateRes,
      msg: '用户信息更新成功'
    };
  } catch(e) {
    console.error('更新用户失败:', e);
    return { code: 500, msg: '更新用户失败: ' + e.message };
  }
}

// 删除用户
async function deleteUser(params, context) {
  const { userId } = params;
  
  if(!userId) {
    return { code: 400, msg: '用户ID不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    const deleteRes = await usersCollection.doc(userId).remove();
    
    return {
      code: 0,
      data: deleteRes,
      msg: '用户删除成功'
    };
  } catch(e) {
    console.error('删除用户失败:', e);
    return { code: 500, msg: '删除用户失败: ' + e.message };
  }
}

// 获取用户详情
async function getUserDetail(params, context) {
  const { userId } = params;
  
  if(!userId) {
    return { code: 400, msg: '用户ID不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    // 获取用户完整信息
    const result = await usersCollection.doc(userId).get();
    
    if (!result.data || result.data.length === 0) {
      return { code: 404, msg: '用户不存在' };
    }
    
    const user = result.data[0];
    
    // 删除敏感信息
    delete user.password;
    delete user.token;
    
    return {
      code: 0,
      data: user,
      msg: '获取用户详情成功'
    };
  } catch(e) {
    console.error('获取用户详情失败:', e);
    return { code: 500, msg: '获取用户详情失败: ' + e.message };
  }
}

// 获取用户统计数据（与小程序端 getUserStats 完全一致）
async function getUserStats(params, context) {
  const { userId } = params;
  
  if(!userId) {
    return { code: 400, msg: '用户ID不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    
    console.log('【getUserStats】开始查询用户统计，userId:', userId, 'type:', typeof userId);
    
    // 1. 任务统计 - 与小程序端完全一致
    const taskListRes = await db.collection('taskList')
      .where({ publisher_id: userId })
      .get();
    
    const receivedTaskRes = await db.collection('taskList')
      .where({ receiver_id: userId })
      .get();
    
    // 计算任务统计
    const publishedCount = taskListRes.data.length; // 发布任务数
    const completedCount = taskListRes.data.filter(task => task.status === 'completed').length; // 完成任务数（作为发布者）
    const processingCount = receivedTaskRes.data.filter(task => task.status === 'processing').length; // 进行中任务数（作为接单者）
    const receivedCompletedCount = receivedTaskRes.data.filter(task => task.status === 'completed').length; // 已完成任务数（作为接单者）
    const taskReceivedCount = processingCount + receivedCompletedCount; // 领取任务数 = 进行中 + 已完成（作为接单者）
    
    // 2. 圈子统计 - 与小程序详情页 user-quanzi.vue 完全一致
    const dbCmd = db.command;
    
    // 发帖数：统计所有帖子（包括已发布和未发布）- 与 getUserStats 云函数一致
    const circleRes = await db.collection('add-content')
      .where({ 
        user_id: userId, 
        content_type: 'post'
        // 不过滤 status，统计所有帖子
      })
      .get();
    
    // 评论数：只查询 author_id（与原始 getUserStats 一致）
    const commentRes = await db.collection('user-comment')
      .where({ author_id: userId })
      .get();
    
    console.log('【getUserStats】评论查询结果:', { 
      userId, 
      count: commentRes.data.length,
      sampleData: commentRes.data.slice(0, 2)
    });
    
    // 计算圈子统计
    const postCount = circleRes.data.length;
    const commentCount = commentRes.data.length;
    
    // 获赞数：累加所有帖子的点赞数（不管是否已发布）
    const likeCount = circleRes.data.reduce((sum, post) => sum + (post.like_count || 0), 0);
    
    // 获取用户点赞数据（用户点赞了多少内容）
    const userLikesRes = await db.collection('user-likes')
      .where({ user_id: userId })
      .count();
    
    console.log('【getUserStats】用户点赞查询结果:', { 
      userId, 
      total: userLikesRes.total,
      userLikesRes 
    });
    
    const userLikesCount = userLikesRes.total || 0;
    
    // 3. 活动统计 - 与小程序端 getUserStats 完全一致
    // 发布活动：统计所有活动（不过滤 status）
    const activityRes = await db.collection('add-content')
      .where({ 
        user_id: userId, 
        content_type: 'activity'
        // 不过滤 status，统计所有活动
      })
      .get();
    
    // 参与活动：统计所有参与记录
    const activityParticipantRes = await db.collection('activity_participants')
      .where({ user_id: userId })
      .get();
    
    console.log('【getUserStats】活动统计:', { 
      published: activityRes.data.length,
      participated: activityParticipantRes.data.length
    });
    
    // 计算活动统计
    const publishedActivityCount = activityRes.data.length;
    const participatedActivityCount = activityParticipantRes.data.length;
    
    return {
      code: 0,
      data: {
        // 任务统计
        taskPublished: publishedCount,
        taskReceived: taskReceivedCount, // 领取任务 = 进行中 + 已完成（作为接单者）
        taskProcessing: processingCount,
        taskCompleted: completedCount,
        // 圈子统计
        postsPublished: postCount,
        commentsPublished: commentCount,
        likesReceived: likeCount,
        myLikes: userLikesCount,
        // 活动统计
        activitiesPublished: publishedActivityCount,
        activitiesParticipated: participatedActivityCount
      },
      msg: '获取用户统计成功'
    };
  } catch(e) {
    console.error('获取用户统计失败:', e);
    return { code: 500, msg: '获取用户统计失败: ' + e.message };
  }
}

// 获取违规记录列表
async function getViolations(params, context) {
  const { userId } = params;
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    let violations = [];
    
    if (userId) {
      // 获取单个用户的违规记录
      const userRes = await usersCollection.doc(userId).get();
      if (userRes.data && userRes.data.length > 0) {
        const user = userRes.data[0];
        const records = user.violation_records || [];
        
        // 为每条记录添加用户信息
        violations = records.map(record => ({
          ...record,
          _id: record.mark_time || Date.now(), // 使用时间戳作为ID
          user_id: userId,
          username: user.username,
          nickname: user.nickname,
          violation_count: user.violation_count || 0
        }));
      }
    } else {
      // 获取所有用户的违规记录
      const usersRes = await usersCollection
        .where({
          violation_count: db.command.gt(0)
        })
        .field({
          username: true,
          nickname: true,
          violation_count: true,
          violation_records: true
        })
        .get();
      
      // 展开所有用户的违规记录
      usersRes.data.forEach(user => {
        const records = user.violation_records || [];
        records.forEach(record => {
          violations.push({
            ...record,
            _id: `${user._id}_${record.mark_time}`, // 组合ID
            user_id: user._id,
            username: user.username,
            nickname: user.nickname,
            violation_count: user.violation_count || 0
          });
        });
      });
      
      // 按时间倒序排序
      violations.sort((a, b) => (b.mark_time || 0) - (a.mark_time || 0));
    }
    
    return {
      code: 0,
      data: violations,
      msg: '获取违规记录成功'
    };
  } catch(e) {
    console.error('获取违规记录失败:', e);
    return { code: 500, msg: '获取违规记录失败: ' + e.message };
  }
}

// 获取违规统计数据
async function getViolationStats(params, context) {
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    // 统计所有用户
    const allUsersRes = await usersCollection.count();
    const totalUsers = allUsersRes.total || 0;
    
    // 统计有违规的用户
    const violationUsersRes = await usersCollection
      .where({
        violation_count: db.command.gt(0)
      })
      .get();
    
    const violationUsers = violationUsersRes.data || [];
    
    // 统计违规总次数
    const totalViolations = violationUsers.reduce((sum, user) => {
      return sum + (user.violation_count || 0);
    }, 0);
    
    // 统计高风险用户（违规5次及以上）
    const highRiskUsers = violationUsers.filter(user => {
      return (user.violation_count || 0) >= 5;
    }).length;
    
    return {
      code: 0,
      data: {
        totalUsers,
        violationUsers: violationUsers.length,
        totalViolations,
        highRiskUsers
      },
      msg: '获取违规统计成功'
    };
  } catch(e) {
    console.error('获取违规统计失败:', e);
    return { code: 500, msg: '获取违规统计失败: ' + e.message };
  }
}

// 添加违规记录
async function addViolation(params, context) {
  const { userId, username, type, reason } = params;
  
  if (!type) {
    return { code: 400, msg: '违规类型不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    let targetUserId = userId;
    
    // 如果没有userId，通过username查找
    if (!targetUserId && username) {
      const userRes = await usersCollection
        .where({ username })
        .get();
      
      if (!userRes.data || userRes.data.length === 0) {
        return { code: 404, msg: '用户不存在' };
      }
      
      targetUserId = userRes.data[0]._id;
    }
    
    if (!targetUserId) {
      return { code: 400, msg: '用户ID或用户名不能为空' };
    }
    
    // 获取当前用户信息
    const userRes = await usersCollection.doc(targetUserId).get();
    if (!userRes.data || userRes.data.length === 0) {
      return { code: 404, msg: '用户不存在' };
    }
    
    const user = userRes.data[0];
    const currentRecords = user.violation_records || [];
    const currentCount = user.violation_count || 0;
    
    // 创建违规记录
    const newRecord = {
      type,
      reason: reason || '',
      mark_time: Date.now(),
      marker: 'admin' // 可以改为从context获取当前登录的管理员
    };
    
    // 更新用户数据
    await usersCollection.doc(targetUserId).update({
      violation_count: currentCount + 1,
      violation_records: [...currentRecords, newRecord]
    });
    
    return {
      code: 0,
      msg: '添加违规记录成功'
    };
  } catch(e) {
    console.error('添加违规记录失败:', e);
    return { code: 500, msg: '添加违规记录失败: ' + e.message };
  }
}

// 删除违规记录
async function deleteViolation(params, context) {
  const { recordId, userId } = params;
  
  if (!userId) {
    return { code: 400, msg: '用户ID不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    // 获取用户信息
    const userRes = await usersCollection.doc(userId).get();
    if (!userRes.data || userRes.data.length === 0) {
      return { code: 404, msg: '用户不存在' };
    }
    
    const user = userRes.data[0];
    let records = user.violation_records || [];
    
    // 通过 mark_time 匹配删除记录
    const originalLength = records.length;
    records = records.filter(record => {
      const id = `${userId}_${record.mark_time}`;
      return id !== recordId && record.mark_time.toString() !== recordId;
    });
    
    if (records.length === originalLength) {
      return { code: 404, msg: '违规记录不存在' };
    }
    
    // 更新用户数据
    await usersCollection.doc(userId).update({
      violation_count: records.length,
      violation_records: records
    });
    
    return {
      code: 0,
      msg: '删除违规记录成功'
    };
  } catch(e) {
    console.error('删除违规记录失败:', e);
    return { code: 500, msg: '删除违规记录失败: ' + e.message };
  }
}

// ==================== 审核模块相关函数 ====================

// 获取待审核内容
async function getPendingAudits(params, context) {
  try {
    const db = uniCloud.database();
    const dbCmd = db.command;
    
    // 获取待审核的任务
    const tasksCollection = db.collection('taskList');
    const tasksRes = await tasksCollection
      .where({
        audit_status: dbCmd.in(['pending', null])
      })
      .orderBy('publish_time', 'desc')
      .limit(100)
      .get();
    
    const tasks = tasksRes.data || [];
    
    // 为每个任务添加发布者信息和进度信息
    const usersCollection = db.collection('uni-id-users');
    for (let task of tasks) {
      // 获取发布者信息
      if (task.publisher_id) {
        const userRes = await usersCollection.doc(task.publisher_id).get();
        if (userRes.data && userRes.data.length > 0) {
          task.publisher_name = userRes.data[0].nickname || userRes.data[0].username;
        }
      }
      
      // 任务进度占位，避免显示随机数据
      task.progress = {
        accepted: 0,
        in_progress: 0,
        completed: 0,
        status: task.status || 'pending'
      };
    }
    
    // 获取待审核的活动（如果有活动表）
    let activities = [];
    try {
      const activitiesCollection = db.collection('activities');
      const activitiesRes = await activitiesCollection
        .where({
          audit_status: dbCmd.in(['pending', null])
        })
        .orderBy('create_time', 'desc')
        .limit(50)
        .get();
      activities = activitiesRes.data || [];
      
      // 添加发布者信息
      for (let activity of activities) {
        if (activity.creator_id) {
          const userRes = await usersCollection.doc(activity.creator_id).get();
          if (userRes.data && userRes.data.length > 0) {
            activity.publisher_name = userRes.data[0].nickname || userRes.data[0].username;
          }
        }
      }
    } catch(e) {
      console.log('活动表不存在或查询失败:', e.message);
    }
    
    // 获取待审核的帖子（如果有帖子表）
    let posts = [];
    try {
      const postsCollection = db.collection('add-content');
      const postsRes = await postsCollection
        .where({
          audit_status: dbCmd.in(['pending', null])
        })
        .orderBy('create_time', 'desc')
        .limit(50)
        .get();
      posts = postsRes.data || [];
      
      // 添加发布者信息
      for (let post of posts) {
        if (post.user_id) {
          const userRes = await usersCollection.doc(post.user_id).get();
          if (userRes.data && userRes.data.length > 0) {
            post.publisher_name = userRes.data[0].nickname || userRes.data[0].username;
          }
        }
      }
    } catch(e) {
      console.log('帖子表不存在或查询失败:', e.message);
    }
    
    return {
      code: 0,
      data: {
        tasks: tasks,
        activities: activities,
        posts: posts
      }
    };
  } catch(e) {
    console.error('获取待审核内容失败:', e);
    return { code: 500, msg: '获取待审核内容失败: ' + e.message };
  }
}

// 审核内容
async function auditContent(params, context) {
  const { contentType, contentId, auditStatus, auditReason } = params;
  
  if (!contentType || !contentId || !auditStatus) {
    return { code: 400, msg: '参数不完整' };
  }
  
  try {
    const db = uniCloud.database();
    let collection;
    
    // 根据内容类型选择对应的集合
    switch(contentType) {
      case 'task':
        collection = db.collection('taskList');
        break;
      case 'activity':
        collection = db.collection('activities');
        break;
      case 'post':
        collection = db.collection('add-content');
        break;
      default:
        return { code: 400, msg: '不支持的内容类型' };
    }
    
    // 更新审核状态
    const updateData = {
      audit_status: auditStatus,
      audit_time: Date.now(),
      audit_reason: auditReason || ''
    };
    
    await collection.doc(contentId).update(updateData);
    
    // 记录审核历史
    try {
      const historyCollection = db.collection('audit_logs');
      const contentRes = await collection.doc(contentId).get();
      const content = contentRes.data[0];
      
      await historyCollection.add({
        content_type: contentType,
        content_id: contentId,
        content_title: content.title || content.content?.substring(0, 50) || '无标题',
        content_desc: content.description || content.content?.substring(0, 100) || '',
        audit_result: auditStatus,
        audit_reason: auditReason || '',
        auditor_name: 'admin', // 实际应该从context获取
        publisher_name: content.publisher_name || '未知',
        audit_time: Date.now()
      });
    } catch(e) {
      console.log('记录审核历史失败:', e.message);
    }
    
    return {
      code: 0,
      msg: '审核成功'
    };
  } catch(e) {
    console.error('审核内容失败:', e);
    return { code: 500, msg: '审核内容失败: ' + e.message };
  }
}

// 获取审核历史
async function getAuditHistory(params, context) {
  try {
    const db = uniCloud.database();
    const dbCmd = db.command;
    
    // 尝试从审核日志表获取
    try {
      const historyCollection = db.collection('audit_logs');
      
      // 获取所有审核日志记录
      const allRecordsRes = await historyCollection
        .orderBy('create_time', 'desc')
        .limit(200)
        .get();
      
      const allRecords = allRecordsRes.data || [];
      console.log('审核日志总记录数:', allRecords.length);
      
      if (allRecords.length > 0) {
        console.log('第一条记录结构:', JSON.stringify(allRecords[0]));
      }
      
      // 准备数据库集合
      const tasksCollection = db.collection('taskList');
      const activitiesCollection = db.collection('activities');
      const postsCollection = db.collection('add-content');
      const usersCollection = db.collection('uni-id-users');
      
      // 处理每条记录，补充完整信息
      const processedData = await Promise.all(allRecords.map(async (record) => {
        // 检测并转换不同的字段命名
        const contentType = record.content_type || record.target_type;
        const auditResult = record.audit_result || record.action;
        const auditTime = record.audit_time || record.create_time;
        const contentId = record.content_id || record.target_id || '';
        const auditReason = record.audit_reason || record.reason || '';
        
        let contentTitle = record.content_title || '无标题';
        let contentDesc = record.content_desc || '';
        let publisherName = record.publisher_name || '未知';
        
        // 如果没有标题，根据 target_id 去对应表查询
        if (contentId && (!record.content_title || record.content_title === '无标题')) {
          try {
            let contentRes = null;
            
            if (contentType === 'task') {
              contentRes = await tasksCollection.doc(contentId).get();
              if (contentRes.data && contentRes.data.length > 0) {
                const task = contentRes.data[0];
                contentTitle = task.title || '无标题';
                contentDesc = task.description || '';
                
                // 获取发布者信息
                if (task.publisher_id) {
                  const userRes = await usersCollection.doc(task.publisher_id).get();
                  if (userRes.data && userRes.data.length > 0) {
                    publisherName = userRes.data[0].nickname || userRes.data[0].username || '未知';
                  }
                }
              }
            } else if (contentType === 'activity') {
              contentRes = await activitiesCollection.doc(contentId).get();
              if (contentRes.data && contentRes.data.length > 0) {
                const activity = contentRes.data[0];
                contentTitle = activity.title || activity.name || '无标题';
                contentDesc = activity.description || activity.content || '';
                
                // 获取发布者信息
                if (activity.creator_id) {
                  const userRes = await usersCollection.doc(activity.creator_id).get();
                  if (userRes.data && userRes.data.length > 0) {
                    publisherName = userRes.data[0].nickname || userRes.data[0].username || '未知';
                  }
                }
              }
            } else if (contentType === 'post') {
              contentRes = await postsCollection.doc(contentId).get();
              if (contentRes.data && contentRes.data.length > 0) {
                const post = contentRes.data[0];
                contentTitle = post.title || post.content?.substring(0, 50) || '无标题';
                contentDesc = post.content?.substring(0, 100) || '';
                
                // 获取发布者信息
                if (post.user_id) {
                  const userRes = await usersCollection.doc(post.user_id).get();
                  if (userRes.data && userRes.data.length > 0) {
                    publisherName = userRes.data[0].nickname || userRes.data[0].username || '未知';
                  }
                }
              }
            }
          } catch(err) {
            console.log('查询内容详情失败:', contentId, err.message);
          }
        }
        
        return {
          _id: record._id,
          content_type: contentType,
          content_id: contentId,
          content_title: contentTitle,
          content_desc: contentDesc,
          audit_result: auditResult,
          audit_reason: auditReason,
          auditor_name: record.auditor_name || 'admin',
          publisher_name: publisherName,
          audit_time: auditTime
        };
      }));
      
      // 只保留审核相关的记录（approved 或 rejected）
      const validData = processedData.filter(record => {
        return record.content_type && 
               record.audit_result && 
               record.audit_time &&
               (record.audit_result === 'approved' || record.audit_result === 'rejected');
      });
      
      // 对记录进行去重，如果同一个内容有多条审核记录，只保留最新的一条
      const uniqueData = [];
      const seenContentIds = new Map(); // 使用 Map 记录已见过的 content_id
      
      for (const record of validData) {
        const key = `${record.content_type}_${record.content_id}`;
        const existing = seenContentIds.get(key);
        
        if (!existing) {
          // 第一次遇到这个内容，直接添加
          seenContentIds.set(key, record);
          uniqueData.push(record);
        } else {
          // 如果已存在，比较时间，保留最新的
          const existingTime = new Date(existing.audit_time).getTime();
          const currentTime = new Date(record.audit_time).getTime();
          
          if (currentTime > existingTime) {
            // 当前记录更新，替换旧记录
            const index = uniqueData.indexOf(existing);
            if (index !== -1) {
              uniqueData[index] = record;
              seenContentIds.set(key, record);
            }
          }
        }
      }
      
      console.log('有效记录数:', validData.length, '去重后记录数:', uniqueData.length);
      
      return {
        code: 0,
        data: uniqueData
      };
    } catch(e) {
      console.log('审核日志表查询失败:', e.message);
      return {
        code: 0,
        data: []
      };
    }
  } catch(e) {
    console.error('获取审核历史失败:', e);
    return { code: 500, msg: '获取审核历史失败: ' + e.message };
  }
}

// 获取审核统计
async function getAuditStats(params, context) {
  try {
    const db = uniCloud.database();
    const dbCmd = db.command;
    const now = Date.now();
    const oneDayAgo = now - 86400000; // 24小时前
    const oneWeekAgo = now - 604800000; // 7天前
    
    let todayCount = 0;
    let weekCount = 0;
    let approvedCount = 0;
    let rejectedCount = 0;
    
    // 尝试从审核日志表统计
    try {
      const historyCollection = db.collection('audit_logs');
      
      // 只统计有效的审核记录
      const baseCondition = {
        content_type: dbCmd.exists(true),
        audit_result: dbCmd.exists(true),
        audit_time: dbCmd.exists(true)
      };
      
      const todayRes = await historyCollection
        .where({
          ...baseCondition,
          audit_time: dbCmd.gte(oneDayAgo)
        })
        .count();
      todayCount = todayRes.total;
      
      const weekRes = await historyCollection
        .where({
          ...baseCondition,
          audit_time: dbCmd.gte(oneWeekAgo)
        })
        .count();
      weekCount = weekRes.total;
      
      const approvedRes = await historyCollection
        .where({
          ...baseCondition,
          audit_result: 'approved',
          audit_time: dbCmd.gte(oneWeekAgo)
        })
        .count();
      approvedCount = approvedRes.total;
      
      const rejectedRes = await historyCollection
        .where({
          ...baseCondition,
          audit_result: 'rejected',
          audit_time: dbCmd.gte(oneWeekAgo)
        })
        .count();
      rejectedCount = rejectedRes.total;
    } catch(e) {
      console.log('审核日志表不存在，返回零统计以避免模拟数据');
      todayCount = 0;
      weekCount = 0;
      approvedCount = 0;
      rejectedCount = 0;
    }
    
    const total = approvedCount + rejectedCount;
    const approveRate = total > 0 ? Math.round((approvedCount / total) * 100) : 0;
    const rejectRate = total > 0 ? Math.round((rejectedCount / total) * 100) : 0;
    
    return {
      code: 0,
      data: {
        today: todayCount,
        week: weekCount,
        approveRate: approveRate,
        rejectRate: rejectRate
      }
    };
  } catch(e) {
    console.error('获取审核统计失败:', e);
    return { code: 500, msg: '获取审核统计失败: ' + e.message };
  }
}

// 获取被拒绝内容
async function getRejectedContent(params, context) {
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
  // 获取被拒绝的任务
  const dbCmd = db.command;
  const tasksCollection = db.collection('taskList');
  const tasksRes = await tasksCollection
    .where(dbCmd.or([
      { audit_status: 'rejected' },
      { audit_status: 'reviewed_rejected' },
      { status: 'reviewed_rejected' }
    ]))
    .orderBy('create_time', 'desc')
    .limit(100)
    .get();
  
  const tasks = tasksRes.data || [];
  
  console.log('获取到的任务数量:', tasks.length);
  if (tasks.length > 0) {
    console.log('第一条任务原始数据:', JSON.stringify(tasks[0]));
  }
    
    // 添加发布者信息
    for (let task of tasks) {
      if (task.publisher_id) {
        const userRes = await usersCollection.doc(task.publisher_id).get();
        if (userRes.data && userRes.data.length > 0) {
          task.publisher_name = userRes.data[0].nickname || userRes.data[0].username;
        }
      }
      // 支持多种时间字段
      task.reject_time = task.audit_time || task.update_time || task.create_time;
      // 使用 reject_reason 字段
      const reason = task.reject_reason || task.audit_reason || '';
      task.violation_type = reason ? getViolationType(reason) : '审核未通过';
      task.violation_reason = reason || '未填写具体原因';
      task.auditor_name = 'admin';
      
      console.log('任务处理 - title:', task.title, 'reject_reason:', task.reject_reason, 'violation_reason:', task.violation_reason);
    }
    
  // 获取被拒绝的活动
  let activities = [];
  try {
    const dbCmd = db.command;
    const activitiesCollection = db.collection('activities');
    const activitiesRes = await activitiesCollection
      .where(dbCmd.or([
        { audit_status: 'rejected' },
        { audit_status: 'reviewed_rejected' },
        { status: 'reviewed_rejected' }
      ]))
      .orderBy('create_time', 'desc')
      .limit(50)
      .get();
    activities = activitiesRes.data || [];
    
    console.log('获取到的活动数量:', activities.length);
      
    for (let activity of activities) {
      if (activity.creator_id) {
        const userRes = await usersCollection.doc(activity.creator_id).get();
        if (userRes.data && userRes.data.length > 0) {
          activity.publisher_name = userRes.data[0].nickname || userRes.data[0].username;
        }
      }
      // 支持多种时间字段
      activity.reject_time = activity.audit_time || activity.update_time || activity.create_time;
      // 使用 reject_reason 字段
      const reason = activity.reject_reason || activity.audit_reason || '';
      activity.violation_type = reason ? getViolationType(reason) : '审核未通过';
      activity.violation_reason = reason || '未填写具体原因';
      activity.auditor_name = 'admin';
      
      console.log('活动处理 - title:', activity.title, 'reject_reason:', activity.reject_reason, 'violation_reason:', activity.violation_reason);
    }
    } catch(e) {
      console.log('活动表不存在或查询失败:', e.message);
    }
    
  // 获取被拒绝的帖子
  let posts = [];
  try {
    const dbCmd = db.command;
    const postsCollection = db.collection('add-content');
    const postsRes = await postsCollection
      .where(dbCmd.or([
        { audit_status: 'rejected' },
        { audit_status: 'reviewed_rejected' },
        { status: 'reviewed_rejected' }
      ]))
      .orderBy('create_time', 'desc')
      .limit(50)
      .get();
    posts = postsRes.data || [];
    
    console.log('获取到的帖子数量:', posts.length);
      
    for (let post of posts) {
      if (post.user_id) {
        const userRes = await usersCollection.doc(post.user_id).get();
        if (userRes.data && userRes.data.length > 0) {
          post.publisher_name = userRes.data[0].nickname || userRes.data[0].username;
        }
      }
      // 支持多种时间字段
      post.reject_time = post.audit_time || post.update_time || post.create_time;
      // 使用 reject_reason 字段
      const reason = post.reject_reason || post.audit_reason || '';
      post.violation_type = reason ? getViolationType(reason) : '审核未通过';
      post.violation_reason = reason || '未填写具体原因';
      post.auditor_name = 'admin';
      
      // 帖子内容字段可能是content
      if (!post.description && post.content) {
        post.description = post.content;
      }
      
      console.log('帖子处理 - title:', post.title, 'content:', post.content?.substring(0, 20), 'reject_reason:', post.reject_reason, 'violation_reason:', post.violation_reason);
    }
    } catch(e) {
      console.log('帖子表不存在或查询失败:', e.message);
    }
    
    return {
      code: 0,
      data: {
        tasks: tasks,
        activities: activities,
        posts: posts
      }
    };
  } catch(e) {
    console.error('获取被拒绝内容失败:', e);
    return { code: 500, msg: '获取被拒绝内容失败: ' + e.message };
  }
}

// 恢复被拒绝内容到待审核状态
async function restoreRejectedContent(params, context) {
  const { contentType, contentId } = params;
  
  if (!contentType || !contentId) {
    return { code: 400, msg: '参数不完整' };
  }
  
  try {
    const db = uniCloud.database();
    let collection;
    
    switch(contentType) {
      case 'task':
        collection = db.collection('taskList');
        break;
      case 'activity':
        collection = db.collection('activities');
        break;
      case 'post':
        collection = db.collection('add-content');
        break;
      default:
        return { code: 400, msg: '不支持的内容类型' };
    }
    
    // 恢复到待审核状态
    await collection.doc(contentId).update({
      audit_status: 'pending',
      audit_time: null,
      audit_reason: ''
    });
    
    return {
      code: 0,
      msg: '恢复成功'
    };
  } catch(e) {
    console.error('恢复内容失败:', e);
    return { code: 500, msg: '恢复内容失败: ' + e.message };
  }
}

// 永久删除被拒绝内容
async function deleteRejectedContent(params, context) {
  const { contentType, contentId } = params;
  
  if (!contentType || !contentId) {
    return { code: 400, msg: '参数不完整' };
  }
  
  try {
    const db = uniCloud.database();
    let collection;
    
    switch(contentType) {
      case 'task':
        collection = db.collection('taskList');
        break;
      case 'activity':
        collection = db.collection('activities');
        break;
      case 'post':
        collection = db.collection('add-content');
        break;
      default:
        return { code: 400, msg: '不支持的内容类型' };
    }
    
    // 永久删除
    await collection.doc(contentId).remove();
    
    return {
      code: 0,
      msg: '删除成功'
    };
  } catch(e) {
    console.error('删除内容失败:', e);
    return { code: 500, msg: '删除内容失败: ' + e.message };
  }
}

// 辅助函数：根据审核原因判断违规类型
function getViolationType(reason) {
  if (!reason) return '其他违规';
  
  const reasonLower = reason.toLowerCase();
  
  if (reasonLower.includes('虚假') || reasonLower.includes('欺诈') || reasonLower.includes('假')) {
    return '虚假信息';
  }
  if (reasonLower.includes('违法') || reasonLower.includes('违规') || reasonLower.includes('非法')) {
    return '违法违规';
  }
  if (reasonLower.includes('低俗') || reasonLower.includes('色情') || reasonLower.includes('暴力')) {
    return '低俗内容';
  }
  if (reasonLower.includes('广告') || reasonLower.includes('营销') || reasonLower.includes('推广')) {
    return '垃圾广告';
  }
  if (reasonLower.includes('侵权') || reasonLower.includes('抄袭') || reasonLower.includes('盗用')) {
    return '侵权内容';
  }
  
  return '其他违规';
}
